import json
import requests
import random
from hashlib import md5

from django.http import JsonResponse
from django.contrib.auth.hashers import make_password, check_password
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from .models import User

requests.packages.urllib3.disable_warnings()


def random_username():
    return 'bbd_' + str(random.randint(100000, 999999999))


def login_qq(req):
    """
    QQ登陆逻辑
    :param req: 
    :return: 
    """
    # qq_flag = req.GET.get('qq', '')
    access_token = req.GET.get('access_token', '')
    expires_in = req.GET.get('expires_in', '')

    def _get_user_info(access_token, expires_in):
        token_url = 'https://graph.qq.com/oauth2.0/me'
        # user_url = 'https://graph.qq.com/user/get_user_info'

        token_text = requests.get(token_url, params={
            'access_token': access_token,
            'expires_in': expires_in
        }, verify=False).text

        token_text_start = token_text.index('{')
        token_text_end = token_text.index('}')
        user_params = json.loads(token_text[token_text_start: token_text_end + 1], encoding='utf-8')

        # user_params.update({'access_token': access_token, 'appid': 101580560})
        #
        # user_text = requests.get(user_url, params=user_params, verify=False).text
        #
        # user_text_start = user_text.index('{')
        # user_text_end = user_text.index('}')
        #
        # return json.loads(user_text[user_text_start:user_text_end + 1], encoding='utf8')
        return user_params

    user_info = _get_user_info(access_token, expires_in)

    openid = user_info.get('openid', '')
    if openid:
        user_obj = User.objects.filter(openid=openid)
        if user_obj:
            user = user_obj.first()
        else:
            m = md5()
            m.update(str(random_username()).encode())

            user = User.objects.create(username=random_username(), password=make_password(m.hexdigest()),
                                       openid=openid)
        login(req, user)
    return redirect('/')


def base_login(req):
    """
    普通登陆逻辑
    :param req:
    :return:
    """

    def _get_data(req):
        return json.loads(req.body.decode('utf8'))

    kwargs = {}
    if req.method == 'GET':
        if req.user.is_authenticated:
            return redirect('/')
        kwargs['action'] = "登陆"
        return render(req, 'login.html', kwargs)

    user_info = _get_data(req)
    user = authenticate(username=user_info['username'], password=user_info['password'])

    if user is None:
        kwargs['action'] = "登陆"
        kwargs['message'] = '用户名或密码不正确'
        return JsonResponse(kwargs)
    kwargs['message'] = '登陆成功'
    kwargs['login_code'] = 302
    login(req, user)
    return JsonResponse(kwargs)
